package com.example.javafx.bilibilidownload.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程管理对象
 */
@Data
public class ExecutorServiceForTransform {

    private static final Logger log = LogManager.getLogger(ExecutorServiceForTransform.class);

    private int poolSize = 6;

    private volatile ThreadPoolExecutor pool;

    private volatile AtomicInteger success = new AtomicInteger(0);

    private volatile int count;

    public ExecutorServiceForTransform(int poolSize) {
        this.poolSize = poolSize;
        pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.poolSize);
    }

    public ExecutorServiceForTransform() {
        pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.poolSize);
    }

    public boolean check() {
        //如果还有线程，就加入进去，否则就不加
        if (pool.getActiveCount() < poolSize && pool.getQueue().size() < 1) {
            return true;
        } else {
            return false;
        }
    }

    public void addThread(Runnable transcodeThread) {
        //如果还有线程，就加入进去，否则就不加
        pool.submit(transcodeThread);
    }

    /**
     * @Description: 判断线程池是否有东西，有就返回true
     * @Param:
     * @return:
     * @Author: Mr.zengbang
     * @Date: 2020/9/6
     */
    public void shutDown() {
        while (!isFinish()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        while (success.get() != count) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("没有任务了，线程可以自动关闭了！");
        pool.shutdown();
    }

    /**
     * @Description:判断当前线程池是否还有任务，有任务没做完返回false，任务全部做完返回true
     * @Param: []
     * @return: boolean
     * @Author: Mr.zengbang
     * @Date: 2021/1/15
     */
    public boolean isFinish() {

        if ((pool.getTaskCount() - pool.getCompletedTaskCount()) > 0 || pool.getActiveCount() > 0) {
            return false;
        }
        return true;
    }
}
